package com.rskj.cashbook.Interceptor;

import com.rskj.cashbook.iexception.BusinessException;
import com.rskj.cashbook.iexception.TokenExpiredException;
import com.rskj.cashbook.util.JwtUtil;
import com.rskj.cashbook.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private JwtUtil jwtUtil = new JwtUtil();
    private static final List<String> WHITELIST = Arrays.asList("/user/login", "/user/register",
            "/error", "user/up/passwd");

    @Resource
    RedisUtil redisUtil;

    @Resource
    private HandlerExceptionResolver handlerExceptionResolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        log.debug("Processing request: {}", requestURI);

        if (WHITELIST.stream().anyMatch(requestURI::contains)) {
            log.debug("Request {} is in whitelist, skipping authentication", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Authorization");
        log.debug("Authorization header: {}", token);

        if (StringUtils.isBlank(token) || !token.startsWith("Bearer ")) {
            log.warn("Invalid token format: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            handlerExceptionResolver.resolveException(request, response, null, new BusinessException("token传参不对"));
            return;
        }

        token = token.substring(7);
        log.debug("Extracted token: {}", token);

        String username = null;
        String deviceId = null;
        try {
            username = jwtUtil.extractUsername(token);
            deviceId = jwtUtil.extractDeviceId(token);
            log.debug("Extracted username: {}, deviceId: {}", username, deviceId);
        } catch (Exception e) {
            log.error("Error extracting username or deviceId from token: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            handlerExceptionResolver.resolveException(request, response, null, new BusinessException("JWT解析失败: " + e.getMessage()));
            return;
        }

        if (StringUtils.isBlank(username)) {
            log.warn("Username is null or blank after extraction");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            handlerExceptionResolver.resolveException(request, response, null, new BusinessException("Invalid JWT Token: username is null"));
            return;
        }

        if (StringUtils.isBlank(deviceId)) {
            log.warn("DeviceId is null or blank after extraction");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            handlerExceptionResolver.resolveException(request, response, null, new BusinessException("Invalid JWT Token: deviceId is null"));
            return;
        }

        // 使用username:deviceId作为Redis key
        String rediskey = JwtUtil.getTokenKey(username, deviceId);
        log.debug("Redis key: {}", rediskey);
        
        boolean flag = redisUtil.exists(rediskey);
        log.debug("Token exists in Redis: {}", flag);

        if (!flag || !jwtUtil.validateToken(token, username)) {
            log.warn("Token validation failed for user: {}, deviceId: {}", username, deviceId);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // 抛出TokenExpiredException而不是BusinessException
            handlerExceptionResolver.resolveException(request, response, null, new TokenExpiredException("token过期"));
            return;
        }

        log.debug("Authentication successful for user: {}, deviceId: {}", username, deviceId);
        Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
